package accountdao

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/db"
	"xr-game-server/entity"
)

var accountCacheMgr *cache.CacheMgr

// GetAccountBy 根据玩家id拉取数据
func GetAccountBy(openId string, channel uint) *entity.Account {
	key := fmt.Sprintf("%v:%v", openId, channel)
	//命中不了缓存，从数据库拉取数据
	cacheData := accountCacheMgr.GetData(key, func(ctx context.Context) (value interface{}, err error) {
		//从数据库拉取数据
		var account *entity.Account
		err = g.Model(string(entity.TbAccount)).Unscoped().Where(g.Map{
			string(entity.AccountOpenId):  openId,
			string(entity.AccountChannel): channel,
		}).Scan(&account)
		if account != nil {
			return account, nil
		} else {
			return entity.NewAccount(openId, channel), nil
		}

	})
	return cacheData.(*entity.Account)
}

func GetAccountById(accountId uint64) *entity.Account {
	//从数据库拉取数据
	var account *entity.Account
	g.Model(string(entity.TbAccount)).Unscoped().Where(db.IdName, accountId).Scan(&account)
	if account != nil {
		return account
	} else {
		return nil
	}
}

func InitAccountDao() {
	accountCacheMgr = cache.NewCacheMgr()
}
